﻿using Inovout.Kuajing.Models;
using Inovout.Kuajing.Services;
using Inovout.Services;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Inovout.Kuajing.Web.Controllers
{
    public class LogisticsController : ApiController
    {
        private ShipmentOrderService shipmentOrderService = ComponentRegistry.Resolve<ShipmentOrderService>();
        private IRepositoryService<LogisticsLog> logisticsLogService = ComponentRegistry.Resolve<IRepositoryService<LogisticsLog>>();
        [Route("v1/logistics/{logistics_code}/trace")]
        [HttpGet]
        public JObject GetTraces(string logistics_code)
        {
            var traces = logisticsLogService.Query().Where(l => l.LogisticsOrderNo.Equals(logistics_code)).OrderBy(l => l.OperationDate);

            JObject result = new JObject();
            result["logistics_code"] = logistics_code;
            result["trace"] = JArray.FromObject(traces);
            return result;

        }

        [Route("v1/logistics/{logistics_code}/status")]
        [HttpGet]
        public JObject GetStatus(string logistics_code)
        {
            var order = shipmentOrderService.GetByLogisticsCode(logistics_code);
            JObject result = new JObject();
            result["logistics_code"] = logistics_code;
            result["status"] = "Pending";
            if (order != null)
            {
                if (order.Status < ShipmentOrderStatus.Shipped)
                {
                    result["status"] = "Packaged";
                }
                else if (order.Status >= ShipmentOrderStatus.Shipped && order.Status < ShipmentOrderStatus.Received)
                {
                    result["status"] = "Shipped";
                }
                else if (order.Status == ShipmentOrderStatus.Received)
                {
                    result["status"] = "Received";
                }
                else if (order.Status == ShipmentOrderStatus.Closed)
                {
                    result["status"] = "Closed";
                }
            }
            return result;
        }
    }
}
